#include "stdafx.h"
#include <comdef.h>
#include "DatabaseAdapter.h"
#include "OracleAdapter.h"
#include "Infobus.h"

#include <string>
#include <windows.h>

#define GUID_STRING_LEN 64

DatabaseAdapter * DatabaseAdapter::getInstance(E_SUBJECT subj)
{
  return new SQLServerAdapter(subj);
}

DatabaseAdapter::DatabaseAdapter(E_SUBJECT subj)
  : cnOpen(false)
  , pMsg(NULL)
  , subject(subj)
  , m_pListener(NULL)
  , m_bAliveBeats(false)
{
  memset(szSender, 0, sizeof(szSender));

  GUID guid;
  CoCreateGuid(&guid);

  OLECHAR szGuid[GUID_STRING_LEN]={0};
  int nCount = ::StringFromGUID2(guid, szGuid, GUID_STRING_LEN);
  _bstr_t bstrGuid = szGuid;
  std::string s = std::string(bstrGuid);
  strncpy(szSender, s.substr(1,s.length()-2).c_str(), sizeof(szSender)-1);
}

DatabaseAdapter::~DatabaseAdapter()
{
  if (pMsg) delete pMsg;
}

void DatabaseAdapter::setAliveBeats(bool bEnable)
{
  m_bAliveBeats = bEnable;
}

const char* DatabaseAdapter::getSender()
{
  return this->szSender;
}

const char* DatabaseAdapter::getSubjectText() 
{
  return SubjectText(this->subject);
}

void DatabaseAdapter::setListener(IListener * pListen)
{
  m_pListener = pListen;
}

E_SUBJECT DatabaseAdapter::SubjectEnum(const char* s)
{
  if (_bstr_t(s) == _bstr_t("TRACES")) return TRACES;
  else if (_bstr_t(s) == _bstr_t("EVENTS")) return EVENTS;
  else if (_bstr_t(s) == _bstr_t("ACTIONS")) return ACTIONS;
  else if (_bstr_t(s) == _bstr_t("COMMANDS")) return COMMANDS;
  else if (_bstr_t(s) == _bstr_t("METADATA")) return METADATA;
  else return UNKNOWN;
}

char DatabaseAdapter::m_szTmpSubj[256];

const char* DatabaseAdapter::SubjectText(E_SUBJECT s)
{
  memset(m_szTmpSubj, 0, sizeof(m_szTmpSubj));
  switch (s) {
    case TRACES:
      strncpy(m_szTmpSubj, _bstr_t("TRACES"), sizeof(m_szTmpSubj)-1);
      break;
    case EVENTS:
      strncpy(m_szTmpSubj, _bstr_t("EVENTS"), sizeof(m_szTmpSubj)-1);
      break;
    case ACTIONS:
      strncpy(m_szTmpSubj, _bstr_t("ACTIONS"), sizeof(m_szTmpSubj)-1);
      break;
    case COMMANDS:
      strncpy(m_szTmpSubj, _bstr_t("COMMANDS"), sizeof(m_szTmpSubj)-1);
      break;
    case METADATA:
      strncpy(m_szTmpSubj, _bstr_t("METADATA"), sizeof(m_szTmpSubj)-1);
      break;
    default:
      strncpy(m_szTmpSubj, _bstr_t("UNKNOWN"), sizeof(m_szTmpSubj)-1);
  };
  return m_szTmpSubj;
}



